import { createWebHistory, createRouter,RouterOptions } from 'vue-router'
import useSettingStore from '@/stores/setting';

const routes = [
  {
    path: '/',
    redirect: '/index',
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/home/index.vue'),
    children:[
      {
        path: '/index',
        name: 'index',
        component: () => import('@/views/index/index.vue'),
      },
      {
        path: '/alarm',
        name: 'alarm',
        component: () => import('@/views/alarm/index.vue'),
      },
      {
        path: '/statistics/:page',
        name: 'statistics',
        component: () => import('@/views/statistics/index.vue'),
        props: true,
      },
      {
        path: '/scale/:page',
        name: 'scale',
        component: () => import('@/views/scale/index.vue'),
        props: true,
      },
      {
        path: '/sieves/:page',
        name: 'sieves',
        component: () => import('@/views/sieves/index.vue'),
        props: true,
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_SERVER_PATH),
  routes: routes,
} as RouterOptions);

router.beforeEach((to, from, next) => {
  let param:string = '0'
  let type: number = 0
  let activeName: number = 0
  if (to.path.startsWith('/scale')){
    param = to.path.substring(to.path.lastIndexOf('/')+1);
    activeName = Number(param)
    type = 1
  } else if (to.path.startsWith('/sieves')){
    param = to.path.substring(to.path.lastIndexOf('/')+1);
    type = 2
  } else if (to.path.startsWith('/statistics')){
    param = to.path.substring(to.path.lastIndexOf('/')+1);
    type = 3
  }
  useSettingStore().setSettingActiveName(activeName)
  useSettingStore().setCurrentIndex(param ,type)
  next()
});
export default router;